package com.itic.mall.timer.jdproductbao;

import java.util.Date;

import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.RandomStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.UserSessionHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.mobile.jd.MallJdConfig;
import com.itic.mall.system.productjd.persistence.model.ProductJd;
import com.itic.mall.system.productjd.persistence.model.ProductJdExample;
import com.itic.mall.system.productjd.service.ProductJdService;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.request.cps.UnionThemeGoodsServiceQueryExplosiveGoodsRequest;
import com.jd.open.api.sdk.response.cps.UnionThemeGoodsServiceQueryExplosiveGoodsResponse;

public class JdProductBaoTimer extends BaseMobileInterface {

	private ProductJdService productJdService;

    public void setProductJdService(ProductJdService productJdService) {
        this.productJdService = productJdService;
    }

	public void execute() throws Exception {
		String SERVER_URL = MallJdConfig.getUrl();//搜索有效商品信息
    	String accessToken = MallJdConfig.getAccesstoken();
    	String appKey = MallJdConfig.getKey();
    	String appSecret = MallJdConfig.getSecret();
    	
        JdClient client=new DefaultJdClient(SERVER_URL,accessToken,appKey,appSecret);

    	UnionThemeGoodsServiceQueryExplosiveGoodsRequest request=new UnionThemeGoodsServiceQueryExplosiveGoodsRequest();
    	String conJdStart = sysSettingService.getByKey("BAO_JD_STRRT_PRODUCT");
    	
    	request.setFrom( Integer.parseInt(conJdStart) );
    	request.setPageSize( 100 );

    	UnionThemeGoodsServiceQueryExplosiveGoodsResponse response=client.execute(request);

    	if( "0".equals(response.getCode()) ){
    		String queryExplosiveGoodsResult = response.getQueryExplosiveGoodsResult();
    		if( queryExplosiveGoodsResult.contains("data")){
    			net.sf.json.JSONObject object = new net.sf.json.JSONObject();
				@SuppressWarnings("static-access")
				net.sf.json.JSONObject fromObject = object.fromObject(queryExplosiveGoodsResult);
				syncData(fromObject);
				String addString = NumberStringHelper.addString(conJdStart, "100");
		    	sysSettingService.editByKey("BAO_JD_STRRT_PRODUCT", addString);
    		}
    	}

	}
        
	
		public void syncData( net.sf.json.JSONObject jsonObject2 ){
			net.sf.json.JSONArray jsonArray = jsonObject2.getJSONArray("data");
  			//System.out.println(jsonArray);
  			if( jsonArray.size() > 0 ){
  				for( int i=0; i<jsonArray.size(); i++ ){
  					net.sf.json.JSONObject jsonObject3 = jsonArray.getJSONObject(i);
  					String skuId = jsonObject3.getString("skuId");// balance: 1:已结算，2：未结算;
  					ProductJd jd = productJdService.getBySku(skuId);
  					
  					String adowner = jsonObject3.getString("adowner");// balance: 1:已结算，2：未结算;
  					String commission = jsonObject3.getString("commission");// balance: 1:已结算，2：未结算;
  					String couponNote = jsonObject3.getString("couponNote");// balance: 1:已结算，2：未结算;
  					String couponTab = jsonObject3.getString("couponTab");// balance: 1:已结算，2：未结算;
  					String discountPrice = jsonObject3.getString("discountPrice");// balance: 1:已结算，2：未结算;
  					
  					String discountRate = jsonObject3.getString("discountRate");// balance: 1:已结算，2：未结算;
  					Long endTime = jsonObject3.getLong("endTime");// balance: 1:已结算，2：未结算;
  					Date date = new Date(endTime);
  					String endTimeStr = DateHelper.formatDateTime(date);
  					
  					String exPrice = jsonObject3.getString("exPrice");// balance: 1:已结算，2：未结算;
  					String imgUrl = jsonObject3.getString("imgUrl");// balance: 1:已结算，2：未结算;
  					String inOrderComm = jsonObject3.getString("inOrderComm");// balance: 1:已结算，2：未结算;
  					
  					String inOrderCount = jsonObject3.getString("inOrderCount");// balance: 1:已结算，2：未结算;
  					String isLock = jsonObject3.getString("isLock");// balance: 1:已结算，2：未结算;
  					String isPlan = jsonObject3.getString("isPlan");// balance: 1:已结算，2：未结算;
  					String manJianNote = jsonObject3.getString("manJianNote");// balance: 1:已结算，2：未结算;
  					String pcCommission = jsonObject3.getString("pcCommission");// balance: 1:已结算，2：未结算;
  					
  					String pcCommissionShare = jsonObject3.getString("pcCommissionShare");// balance: 1:已结算，2：未结算;
  					String pcPrice = jsonObject3.getString("pcPrice");// balance: 1:已结算，2：未结算;
  					String plan = jsonObject3.getString("plan");// balance: 1:已结算，2：未结算;
  					String prmTab = jsonObject3.getString("prmTab");// balance: 1:已结算，2：未结算;
  					String realRate = jsonObject3.getString("realRate");// balance: 1:已结算，2：未结算;
  					
  					String shopName = jsonObject3.getString("shopName");// balance: 1:已结算，2：未结算;
  					String shopUrl = jsonObject3.getString("shopUrl");// balance: 1:已结算，2：未结算;
  					
  					String skuName = jsonObject3.getString("skuName");// balance: 1:已结算，2：未结算;
  					String skuUrl = jsonObject3.getString("skuUrl");// balance: 1:已结算，2：未结算;
  					
  					String startTime = jsonObject3.getString("startTime");// balance: 1:已结算，2：未结算;
  					String vid = jsonObject3.getString("vid");// balance: 1:已结算，2：未结算;
  					String wlCommission = jsonObject3.getString("wlCommission");// balance: 1:已结算，2：未结算;
  					String wlCommissionShare = jsonObject3.getString("wlCommissionShare");// balance: 1:已结算，2：未结算;
  					String wlPrice = jsonObject3.getString("wlPrice");// balance: 1:已结算，2：未结算;
  					
  					if( null == jd ){//新建
  						ProductJd model = new ProductJd();
  						model.setId(IdGen.uuid());
  						ProductJdExample example = new ProductJdExample();
  						example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
  						int count = productJdService.count(example);
  						model.setReorder(count + 1);
  						model.setCreateTime(new Date());
  						model.setUpdateTime(new Date());
  						model.setCreateUser(null != UserSessionHelper.get(Constants.USER_ID)
  								? UserSessionHelper.get(Constants.USER_ID) : "unknown");
  						model.setOrgCode(null != UserSessionHelper.get(Constants.USER_ORG)
  								? UserSessionHelper.get(Constants.USER_ORG) : "unknown");
  						model.setIsEffective(DBConst.TRUE);
  						model.setProDesc(couponNote);
  						//model.setJdId(p.getString("jdId"));
  						//model.setCategoryName(p.getString("categoryName"));
  						//model.setGoodsInventory(p.getString("goodsInventory"));
  						///model.setParentId(p.getString("parentId"));
  						model.setConExpireDate(endTimeStr);
  						model.setOriPrice(wlPrice);
  						//model.setConUrl(p.getString("conUrl"));
  						model.setGoodsUrl(imgUrl);
  						//model.setConTicketPrice();

  						//model.setCompetitive(p.getString("competitive"));
  						//model.setRawId(p.getString("id"));
  						model.setSku(skuId);
  						//model.setConUrlB(p.getString("conUrlB"));
  						model.setGoodsName(skuName);
  						model.setConPrice(wlPrice);
  						model.setTotalSales(RandomStringHelper.randomNumStr(4));
  						model.setConTicketPrice("0");
  						
  						 
  						// String subtractString =
  						// NumberStringHelper.subtractString(p.getString("oriPrice"),
  						// p.getString("conTicketPrice"));
  						String profit = NumberStringHelper.divString(wlCommission, "1.8", 2);

  						String dianzhuCommission = profit;
  						// 佣金除以百分之
  						model.setCommissionProfit(dianzhuCommission);
  						String dianzhuCommissionPercent = getDianzhuCommissionProfit(dianzhuCommission,wlPrice);
  						// 计算店主的佣金 比
  						model.setCommission(dianzhuCommissionPercent);
  						productJdService.add(model);

  						System.out.println("成功同步了京东商品" + model.getGoodsName());
  						
  					}else{//更新
  						jd.setGoodsUrl(imgUrl);
  						jd.setConPrice(wlPrice);
  						jd.setOriPrice(wlPrice);
  						jd.setGoodsName(skuName);
  						
  						String profit = NumberStringHelper.divString(wlCommission, "1.8", 2);

  						String dianzhuCommission = profit;
  						String dianzhuCommissionPercent = getDianzhuCommissionProfit(dianzhuCommission,wlPrice);
  						jd.setCommission(dianzhuCommissionPercent);
  						jd.setCommissionProfit(dianzhuCommission);
  						productJdService.edit(jd);
  					}
  					
  				}
  			}
	}
        
        /**
         * 计算店主的佣金
         * @return
         */
        public String getDianzhuCommission(String commission){
        	//京东扣除百分之十
        	String jdPercent="10";
        	String byKey = sysSettingService.getByKey("JD_MARKET_PROFIT_PERCENT");
        	if( StringHelper.isNotBlank(byKey) ){
        		jdPercent=byKey;
        	}
        	String divString = NumberStringHelper.divString(jdPercent, "100", 2);
        	String jdProfit = NumberStringHelper.mulString(commission, divString);//结算到京东的利润
        	
        	String backProfit = NumberStringHelper.subtractString(commission, jdProfit);//这是京东返回给我们的利润
        	
        	//与店主平分下利润
        	String ydProfit = NumberStringHelper.divString(backProfit, "2", 2);//这是给店主的利润
        	
        	return ydProfit;
        }
        
        /**
         * 计算店主的佣金百分比后多少金额
         * @return
         */
        public String getDianzhuCommissionProfit(String dianzhuCommission,String conPrice ){
        	String divString = NumberStringHelper.divString(dianzhuCommission, conPrice, 2);
        	String dianzhuPercent = NumberStringHelper.mulString(divString, "100");
        	return dianzhuPercent;
        }
}